<template>
  <div class="text-to-image-container">
    <div class="btn-animate btn-animate__surround" @click="goToHome">
      <span>点击返回主页面</span>
    </div>
    
    <div class="header">
      <h1>AI文本生图 & 智能翻译</h1>
      <p>输入文本生成图像，支持英文文本生图和中文翻译功能</p>
    </div>

    <div class="main-content">
      <div class="split-container">
        <!-- 左侧：文本生图 -->
        <div class="left-panel">
          <div class="panel-header">
            <h2>
              <i class="el-icon-picture"></i>
              文本生成图像
            </h2>
            <el-tag type="warning" size="mini" effect="plain">
              支持中英文双语言输入
            </el-tag>
          </div>

          <div class="form-section">
            <el-form label-position="top">
              <el-form-item label="英文描述">
                <el-input
                  v-model="imagePrompt"
                  type="textarea"
                  :rows="4"
                  placeholder="例如：a beautiful sunset over the ocean, digital art style"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="图像尺寸">
                <el-select v-model="imageSize" style="width: 100%">
                  <el-option label="512x512 (正方形)" value="512x512" />
                  <el-option label="768x512 (横向)" value="768x512" />
                  <el-option label="512x768 (纵向)" value="512x768" />
                </el-select>
              </el-form-item>

              <el-form-item label="生成数量">
                <el-slider
                  v-model="numImages"
                  :min="1"
                  :max="4"
                  :step="1"
                  show-stops
                  show-input
                />
              </el-form-item>

              <el-button
                type="primary"
                size="large"
                @click="generateImage"
                :loading="isGeneratingImage"
                :disabled="!imagePrompt.trim()"
                class="action-btn full-width"
              >
                <i class="el-icon-magic-stick"></i>
                {{ isGeneratingImage ? '生成中...' : '生成图像' }}
              </el-button>
            </el-form>

            <!-- 生成结果 -->
            <div class="image-results" v-if="generatedImages.length > 0">
              <h3>生成结果</h3>
              <div class="image-grid">
                <div 
                  v-for="(img, index) in generatedImages" 
                  :key="index"
                  class="image-item"
                >
                  <img :src="img.url" :alt="`生成图片 ${index + 1}`" />
                  <div class="image-actions">
                    <el-button 
                      type="text" 
                      size="small" 
                      @click="downloadImage(img.url, index)"
                    >
                      <i class="el-icon-download"></i>
                      下载
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：翻译功能 -->
        <div class="right-panel">
          <div class="panel-header">
            <h2>
              <i class="el-icon-edit"></i>
              智能翻译
            </h2>
            <el-tag type="success" size="mini" effect="plain">
              中英互译
            </el-tag>
          </div>

          <div class="form-section">
            <el-form label-position="top">
              <el-form-item label="源语言">
                <el-select v-model="sourceLang" style="width: 100%">
                  <el-option label="自动检测" value="auto" />
                  <el-option label="中文" value="zh" />
                  <el-option label="英文" value="en" />
                </el-select>
              </el-form-item>

              <el-form-item label="输入文本">
                <el-input
                  v-model="translationText"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入要翻译的文本..."
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="目标语言">
                <el-select v-model="targetLang" style="width: 100%">
                  <el-option label="中文" value="zh" />
                  <el-option label="英文" value="en" />
                </el-select>
              </el-form-item>

              <div class="translation-actions">
                <el-button
                  type="primary"
                  size="large"
                  @click="translateText"
                  :loading="isTranslating"
                  :disabled="!translationText.trim()"
                  class="action-btn"
                >
                  <i class="el-icon-sort"></i>
                  {{ isTranslating ? '翻译中...' : '开始翻译' }}
                </el-button>

                <el-button
                  v-if="translatedResult"
                  type="success"
                  size="large"
                  @click="copyTranslation"
                  class="action-btn"
                >
                  <i class="el-icon-document-copy"></i>
                  复制结果
                </el-button>
              </div>
            </el-form>

            <!-- 翻译结果 -->
            <div class="translation-result" v-if="translatedResult">
              <h3>翻译结果</h3>
              <div class="result-box">
                <p>{{ translatedResult }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 文本生图相关数据
const imagePrompt = ref('');
const imageSize = ref('512x512');
const numImages = ref(1);
const isGeneratingImage = ref(false);
const generatedImages = ref([]);

// 翻译相关数据
const translationText = ref('');
const sourceLang = ref('auto');
const targetLang = ref('zh');
const isTranslating = ref(false);
const translatedResult = ref('');

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 文本生图功能
const generateImage = async () => {
  if (!imagePrompt.value.trim()) {
    ElMessage.warning('请输入英文描述');
    return;
  }

  isGeneratingImage.value = true;
  
  try {
    const response = await fetch('http://localhost:5000/api/generate-image', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt: imagePrompt.value,
        size: imageSize.value,
        num_images: numImages.value
      })
    });

    if (!response.ok) {
      throw new Error('生成失败');
    }

    const result = await response.json();
    
    if (result.success) {
      generatedImages.value = result.images;
      ElMessage.success(`成功生成 ${result.images.length} 张图像`);
    } else {
      throw new Error(result.error || '生成失败');
    }

  } catch (error) {
    console.error('生成图像错误:', error);
    ElMessage.error(error.message || '图像生成失败，请重试');
  } finally {
    isGeneratingImage.value = false;
  }
};

// 下载图片
const downloadImage = (url, index) => {
  const link = document.createElement('a');
  link.href = url;
  link.download = `generated_image_${index + 1}.png`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 翻译功能
const translateText = async () => {
  if (!translationText.value.trim()) {
    ElMessage.warning('请输入要翻译的文本');
    return;
  }

  isTranslating.value = true;
  
  try {
    const response = await fetch('http://localhost:5000/api/translate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text: translationText.value,
        source_lang: sourceLang.value,
        target_lang: targetLang.value
      })
    });

    if (!response.ok) {
      throw new Error('翻译失败');
    }

    const result = await response.json();
    
    if (result.success) {
      translatedResult.value = result.translated_text;
      ElMessage.success('翻译完成');
    } else {
      throw new Error(result.error || '翻译失败');
    }

  } catch (error) {
    console.error('翻译错误:', error);
    ElMessage.error(error.message || '翻译失败，请重试');
  } finally {
    isTranslating.value = false;
  }
};

// 复制翻译结果
const copyTranslation = () => {
  if (translatedResult.value) {
    navigator.clipboard.writeText(translatedResult.value).then(() => {
      ElMessage.success('翻译结果已复制到剪贴板');
    }).catch(() => {
      ElMessage.error('复制失败，请手动复制');
    });
  }
};
</script>

<style scoped>
@import '../assets/TextToImage.css'
</style>
